package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbBrand;
import com.bwie.service.TbBrandService;
import com.bwie.mapper.TbBrandMapper;
import com.bwie.utils.R;
import com.bwie.utils.TokenUtil;
import com.bwie.vo.BrandVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
* @author Lenovo
* @description 针对表【tb_brand(品牌表)】的数据库操作Service实现
* @createDate 2025-07-19 08:43:08
*/
@Service
public class TbBrandServiceImpl extends ServiceImpl<TbBrandMapper, TbBrand>
    implements TbBrandService{

    @Autowired
    TbBrandMapper tbBrandMapper;
    @Autowired
    HttpServletRequest request;

    @Override
    public R getBrandList(BrandVo brandVo) {
        Page<TbBrand> page = new Page<>(brandVo.getPageNum(), brandVo.getPageSize());
        LambdaQueryWrapper<TbBrand> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(brandVo.getKeyWord())){
            wrapper.like(TbBrand::getBrandName,brandVo.getKeyWord());
        }
        wrapper.orderByDesc(TbBrand::getCreateTime);
        Page<TbBrand> tbBrandPage = tbBrandMapper.selectPage(page, wrapper);
        return R.OK(tbBrandPage);
    }

    @Override
    public R addBrand(TbBrand tbBrand) {
        String token = request.getHeader("token");
        if(token == null){
            return R.ERROR(404,"请先登录");
        }
        String userName = TokenUtil.userName(token);

        TbBrand brand = tbBrandMapper.selectOne(
                new LambdaQueryWrapper<TbBrand>().eq(TbBrand::getBrandName, tbBrand.getBrandName())
        );
        if(brand != null){
            return R.ERROR(500,"该品牌已经存在");
        }

        tbBrand.setCreateBy(userName);
        tbBrand.setCreateTime(new Date());

        tbBrandMapper.insert(tbBrand);
        return R.OK();
    }

    @Override
    public R changeBrandStatus(TbBrand tbBrand) {
        String token = request.getHeader("token");
        if(token == null){
            return R.ERROR(404,"请先登录");
        }
        String userName = TokenUtil.userName(token);
        TbBrand brand = tbBrandMapper.selectById(tbBrand.getBrandId());
        if(brand == null){
            return R.ERROR(404,"品牌不存在");
        }
        brand.setBrandStatus(tbBrand.getBrandStatus());
        brand.setUpdateBy(userName);
        brand.setUpdateTime(new Date());
        tbBrandMapper.updateById(brand);
        return R.OK();
    }
}




